import re
# 示例规则，后续可以在列表中增加不同规则
RULES= [ 
        {
            "name":"检测通话中是否出现诈骗话术",
            "rule":".*(微信|QQ|放贷|解冻费|佣金|冻结|提现|兼职|结算).*"
        }
    ]


def analysis_speech(asr_result,obs_url):
    

    response = {
        "asr_result": asr_result,
        "audio_url" : obs_url,
        "audio_duration": asr_result.get("audio_duration"),
        "rules_hit_results": get_hit_rule_detail(asr_result.get('segments')),
 
        }

    return response

def get_hit_rule_detail(asr_segments):
    """返回所有规则的命中详情
    """

    rule_hit_results = [] 

    for rule in RULES:
        hit_rule_result_item = {
            "hit_rule_name": "",
            "hit_rule_items": []
        }
        hit_rule_result_item["hit_rule_items"]=[ build_hit_detail(item, rule['rule'])  for item in asr_segments if build_hit_detail(item, rule['rule']) != None]
        if hit_rule_result_item["hit_rule_items"] == []:
            continue
        else:
            hit_rule_result_item["hit_rule_name"]=rule['name']
            rule_hit_results.append(hit_rule_result_item)

    return rule_hit_results


def build_hit_detail(item,rule):
    """判断语音文本是否被规则命中,若命中返回文本,角色和起始时间

    """

    hit_url_detail_item = {
        "hit_text": "",
        "role": "",
        "start_time":0,
        "end_time": 0
    }

    if re.match(rule,  item['result']['text']) != None:
        hit_url_detail_item['hit_text']=item['result']['text']
        hit_url_detail_item['role']=item['result']['analysis_info']['role']
        hit_url_detail_item['start_time']=item['start_time']
        hit_url_detail_item['end_time']=item['end_time']
        return hit_url_detail_item
    else:
        return None